<?php

namespace Backend\Controllers;

use Models\Alipay;
use Models\AlipayAreply;
use Models\AlipayImg;
use Models\AlipayImgmulti;
use Models\AlipayKeyword;
use Models\AlipayMenu;
use Models\AlipayText;

class AppalipayController extends BaseController
{
    public function beforeExecuteRoute($dispatcher)
    {
        parent::beforeExecuteRoute($dispatcher);
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        if (!$alipay) {
            $this->flash->warning("<a href='admin/config/alipay'>请先点击这里进行支付宝配置，公共配置->支付宝配置</a>");
        }
        $this->view->setVar("alic", $alipay->uid);
    }

    public function indexAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $this->view->setVar('url',$this->config->host."/alipay/index/" . $appid);
        $this->view->setVar('key',$this->config->alipayFuwuRsaPublicKey);
    }

    public function menuAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $menu = AlipayMenu::find("pid=0 AND appid='" . $appid . "'");
        $menu = $menu->toArray();
        foreach ($menu as $key => $vo) {
            $c = AlipayMenu::find("pid=" . $vo['id'] . " AND appid='" . $appid . "'");
            $menu[$key]['sub'] = $c->toArray();
        }
        $this->view->setVar("menu", $menu);
    }


    public function addmenuAction($id)
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        if ($id) {
            if ($this->request->isPost() == true) {
                $menu = AlipayMenu::findFirstByid($id);
                if ($menu->update($this->request->getPost())) {
                    $this->flash->warning("更新成功");
                    $this->view->is_ok = true;
                } else {
                    foreach ($menu->getMessages() as $message) {
                        $this->flash->error((string)$message);
                    }
                }
            }
            $class = AlipayMenu::findFirstByid($id);
            $this->view->setVar("class", $class);
            $menu = AlipayMenu::find("pid=0 AND appid='" . $appid . "'");
            $this->view->setVar("menu", $menu);
        } else {
            if ($this->request->isPost() == true) {
                $menu = new AlipayMenu();
                $menu->appid = $appid;
                if ($menu->create($this->request->getPost())) {
                    $this->flash->warning("保存成功");
                    $this->view->is_ok = true;
                    //$this->response->redirect("admin/appwx/wxmenu");
                } else {
                    foreach ($menu->getMessages() as $message) {
                        $this->flash->error((string)$message);
                    }
                }
            }
            $menu = AlipayMenu::find("pid=0 AND appid='" . $appid . "'");
            $this->view->setVar("menu", $menu);




//            if ($this->request->isPost() == true) {
//                $menu = new AlipayMenu();
//                $menu->appid = $appid;
//                if ($menu->create($this->request->getPost())) {
//                    $this->flash->warning("保存成功");
//                    $this->response->redirect("admin/appalipay/menu");
//                } else {
//                    $this->flash->warning("保存失败");
//                }
//            }
//            $menu = AlipayMenu::find("pid=0 AND appid='" . $appid . "'");
//            $this->view->setVar("menu", $menu);
        }
    }

    public function delmenuAction($id)
    {
        $this->view->disable();
        $menu = AlipayMenu::findFirstByid($id);
        $submenu = AlipayMenu::findBypid($id);
        if ($menu) {
            $menu->delete();
            $submenu->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));

    }


    public function replyAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $reply = AlipayAreply::findFirstByappid($appid);
        if ($reply) {
            if ($this->request->isPost() == true) {
                $reply->updatetime = date("Y-m-d H:i:s", strtotime("now"));
                $reply->check = $this->request->getPost("check");
                if ($reply->update($this->request->getPost())) {
                    $this->flash->warning("更新成功");
                } else {
                    $this->flash->warning("更新失败");
                }
            }
        } else {
            if ($this->request->isPost() == true) {
                $reply = new AlipayAreply();
                $reply->createtime = date("Y-m-d H:i:s", strtotime("now"));
                $reply->updatetime = date("Y-m-d H:i:s", strtotime("now"));
                $reply->appid = $appid;
                if ($reply->create($this->request->getPost())) {
                    $this->flash->warning("保存成功");
                } else {
                    $this->flash->warning("保存失败");
                }
            }
        }
        $this->view->setVar("reply", $reply);
    }

    public function textAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $text = AlipayText::findByappid($appid);
        $this->view->setVar("wxtext", $text);
    }

    public function addtextAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        if ($this->request->isPost() == true) {
            $text = new AlipayText();
            $text->appid = $appid;
            $text->type = 1;
            $text->click = 0;
            $text->createtime = date("Y-m-d H:i:s", strtotime("now"));
            $text->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($text->create($this->request->getPost())) {
                $this->flash->warning("保存成功");
                $keyword = new AlipayKeyword();
                $keyword->pid = $text->id;
                $keyword->appid = $appid;
                $keyword->module = "Text";
                $keyword->create($this->request->getPost());
            } else {
                $this->flash->warning("保存失败");
            }
        }
    }

    public function edittextAction($id)
    {
        if ($this->request->isPost() == true) {
            $text = AlipayText::findFirstByid($id);
            $text->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($text->update($this->request->getPost())) {
                $keyword = AlipayKeyword::findFirst("pid='" . $id . "' AND module='Text'");
                $keyword->update($this->request->getPost());
                $text = AlipayText::findFirstByid($id);
                $this->view->setVar("wxtext", $text);
                return $this->flash->warning("更新成功");
            } else {
                return $this->flash->warning("更新失败");
            }
        }
        $text = AlipayText::findFirstByid($id);
        $this->view->setVar("wxtext", $text);

    }

    public function deltextAction($id)
    {
        $this->view->disable();
        $wxtext = AlipayText::findFirstByid($id);
        $keyword = AlipayKeyword::findFirst("module='Text' AND pid='" . $id . "'");
        if ($wxtext) {
            $wxtext->delete();
            $keyword->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));

    }

    public function imgAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $alipayimg = AlipayImg::findByappid($appid);
        $this->view->setVar("wximg", $alipayimg);
    }

    public function addimgAction()
    {
        $Cuser = $this->Cuser;
        $wx = Alipay::findFirstByuid($Cuser->uid);
        $appid = $wx->appid;
        if ($this->request->isPost() == true) {
            $wximg = new AlipayImg();
            $wximg->appid = $appid;
            $wximg->info = $this->request->getPost('editorValue');
            $wximg->click = 0;
            $wximg->createtime = date("Y-m-d H:i:s", strtotime("now"));
            $wximg->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($wximg->create($this->request->getPost())) {
                $this->flash->warning("保存成功");
                $keyword = new AlipayKeyword();
                $keyword->pid = $wximg->id;
                $keyword->appid = $appid;
                $keyword->module = "Img";
                $keyword->create($this->request->getPost());
            } else {
                $this->flash->warning("保存失败");
            }
        }
    }

    public function editimgAction($id)
    {
        if ($this->request->isPost() == true) {
            $wximg = AlipayImg::findFirstByid($id);
            $wximg->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($wximg->update($this->request->getPost())) {
                $this->flash->warning("更新成功");
                $keyword = AlipayKeyword::findFirst("pid='" . $id . "' AND module='Img'");
                $keyword->update($this->request->getPost());
            } else {
                $this->flash->warning("更新失败");
            }
        }
        $alipayimg = AlipayImg::findFirstByid($id);
        $this->view->setVar("wximg", $alipayimg);
    }

    public function delimgAction($id)
    {
        $this->view->disable();
        $alipayimg = AlipayImg::findFirstByid($id);
        $keyword = AlipayKeyword::findFirst("module='Img' AND pid='" . $id . "'");
        if ($alipayimg) {
            $alipayimg->delete();
            $keyword->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));

    }

    public function selectimgAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $img = AlipayImg::findByappid($appid);
        $this->view->setVar("wximg", $img);
    }

    public function multiAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        $imgmulit = AlipayImgmulti::findByappid($appid);
        $imgmulit = $imgmulit->toArray();
        foreach ($imgmulit as $key => $vo) {
            $id = explode(',', $vo['imgs']);
            foreach ($id as $k => $v) {
                $img = AlipayImg::findFirstByid($v);
                $title[$key][$v] = $img->title;
            }
            $imgmulit[$key]['title'] = $title[$key];
        }
        $this->view->setVar("imgs", $imgmulit);
    }

    public function addmultiAction()
    {
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        $appid = $alipay->appid;
        if ($this->request->isPost() == true) {
            $this->view->disable();
            $imgmulti = new AlipayImgmulti();
            $imgmulti->keyword = $this->request->getPost("key");
            $imgmulti->imgs = $this->request->getPost("id_string");
            $imgmulti->appid = $appid;
            if ($imgmulti->create()) {
                $keyword = new AlipayKeyword();
                $keyword->pid = $imgmulti->id;
                $keyword->keyword = $imgmulti->keyword;
                $keyword->appid = $appid;
                $keyword->module = "Multi";
                $keyword->create($this->request->getPost());
                echo $this->json(1);
            } else {
                echo $this->json(0);
            }
        }

    }

    public function delmultiAction($id)
    {
        $this->view->disable();
        $imgmulti = AlipayImgmulti::findFirstByid($id);
        $keyword = AlipayKeyword::findFirst("module='Multi' AND pid='" . $id . "'");
        if ($imgmulti) {
            $imgmulti->delete();
            $keyword->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));
    }


    public function createmenuAction()
    {
        $config = $this->config;
        $Cuser = $this->Cuser;
        $alipay = Alipay::findFirstByuid($Cuser->uid);
        include $this->config->application->libDir . "alipay/AopSdk.php";

        $client = new \AopClient();
        $client->rsaPrivateKeyFilePath = $config->rsaPrivateKeyPath;
        $client->appId = $alipay->appid;


        $req = new \AlipayMobilePublicMenuGetRequest();
        $resp = $client->execute($req);
        if (property_exists($resp->alipay_mobile_public_menu_get_response, 'menu_content')) {
            //更新菜单
            $r_biz = $this->buildmenu($alipay->appid);
            $req = new \AlipayMobilePublicMenuUpdateRequest();
            $req->setBizContent($r_biz);
            $resp = $client->execute($req);
            if ($resp) {
                $status = 'success';
            } else {
                $status = 'error';
            }
            return json_encode(array('status' => $status));
        } else {
            //创建菜单
            $r_biz = $this->buildmenu($alipay->appid);
            $req = new \AlipayMobilePublicMenuAddRequest();
            $req->setBizContent($r_biz);
            $resp = $client->execute($req);
            if ($resp) {
                $status = 'success';
            } else {
                $status = 'error';
            }
            return json_encode(array('status' => $status));
        }
    }

    public function dashboardAction()
    {

    }
    public function fansAction()
    {

    }

    private function buildmenu($appid)
    {
        $menu = AlipayMenu::find("pid=0 AND appid='" . $appid . "'");
        $menu = $menu->toArray();
        $rule = 0;
        foreach ($menu as $key => $vo) {
            if ($rule < 3) {
                if ($vo['url'] != "") {
                    $newmenu[] = array('actionType' => 'link', 'name' => $vo['title'], 'actionParam' => $vo['url']);
                } else {
                    $newmenu[] = array('actionType' => 'out', 'name' => $vo['title'], 'actionParam' => $vo['keyword']);
                }
                $c = AlipayMenu::find("pid=" . $vo['id'] . " AND appid='" . $appid . "'");
                $rules = 0;
                foreach ($c->toArray() as $a => $i) {
                    if ($rules < 5) {
                        if ($i['url'] != "") {
                            $newmenu[$key]['subButton'][] = array('actionType' => 'link', 'name' => $i['title'], 'actionParam' => $i['url']);
                        } else {
                            $newmenu[$key]['subButton'][] = array('actionType' => 'out', 'name' => $i['title'], 'actionParam' => $i['keyword']);
                        }
                        $rules++;
                    } else
                        break;
                }
                $rule++;
            } else {
                break;
            }
        }
        $obj = array();
        $obj['button'] = $newmenu;
        print_r($obj);
        return json_encode($obj);
    }
}